<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="860px" :title="`${drawerProps.title}商品`">
    <el-form
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="商品大图" prop="goodImg">
        <UploadImg v-model:image-url="drawerProps.row!.goodImg" width="135px" height="135px" :file-size="3">
          <template #empty>
            <el-icon><Avatar /></el-icon>
            <span>请上传商品图</span>
          </template>
          <template #tip> 图片大小不能超过 3M </template>
        </UploadImg>
      </el-form-item>
      <!-- <el-form-item label="商品详情图" prop="photo">
        <UploadImgs v-model:file-list="drawerProps.row!.photo" height="140px" width="140px" border-radius="50%">
          <template #empty>
            <el-icon><Picture /></el-icon>
            <span>请上传照片</span>
          </template>
          <template #tip> 照片大小不能超过 5M </template>
        </UploadImgs>
      </el-form-item> -->
      <el-form-item label="商品名" prop="goodName">
        <el-input v-model="drawerProps.row!.goodName" placeholder="请填写商品名" clearable></el-input>
      </el-form-item>
      <el-form-item label="供应商" prop="supplierId">
        <el-select v-model="drawerProps.row!.supplierId" placeholder="请选择供应商" filterable clearable>
          <el-option v-for="item in drawerProps.SupplierList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="分类" prop="cateId">
        <el-select v-model="drawerProps.row!.cateId" placeholder="请选择分类" filterable clearable>
          <el-option v-for="item in drawerProps.cateList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="规格" prop="specialIds">
        <el-select
          v-model="drawerProps.row!.specialIds"
          placeholder="请选择规格"
          multiple
          filterable
          clearable
          @change="changeSku"
        >
          <el-option v-for="item in SpecialList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
        <el-checkbox-group v-model="checkList" @change="generateSkuTable">
          <el-checkbox v-for="item in tempSkuInfoArray" :key="item.propertiesId" :label="item.propertiesName" />
        </el-checkbox-group>
      </el-form-item>
      <el-table :data="skuData" v-if="skuData.length > 0" border style="width: 100%; margin-bottom: 20px">
        <el-table-column prop="propertiesName" label="规格名称" width="100" />
        <el-table-column prop="price" label="进价" width="140">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.price"
              :precision="2"
              :controls="false"
              :max="999999"
              style="width: 110px"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="tradePrice" label="批发价" width="140">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.tradePrice"
              :precision="2"
              :controls="false"
              :max="999999"
              style="width: 110px"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="showPrice" label="售价" width="140">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.showPrice"
              :precision="2"
              :controls="false"
              :max="999999"
              style="width: 110px"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" width="140">
          <template #default="scope">
            <el-input-number
              :controls="false"
              v-model="scope.row.quantity"
              :precision="0"
              :min="0"
              :max="999999"
              style="width: 110px"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="imageUrl" label="图片">
          <template #default="scope">
            <UploadImg v-model:image-url="scope.row.imageUrl" width="80px" height="80px" :file-size="1">
              <template #empty>
                <el-icon><Avatar /></el-icon>
                <span>请上传规格图</span>
              </template>
              <template #tip> 图片大小不能超过 1M </template>
            </UploadImg>
          </template>
        </el-table-column>
      </el-table>
      <el-form-item label="单位" prop="unitId">
        <el-select v-model="drawerProps.row!.unitId" placeholder="请选择单位" filterable clearable>
          <el-option v-for="item in UnitList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="价格" prop="goodPrice">
        <el-input-number v-model="drawerProps.row!.goodPrice" placeholder="请填写价格" clearable></el-input-number>
      </el-form-item> -->
      <el-form-item label="商品编码" prop="goodCode">
        <el-input v-model="drawerProps.row!.goodCode" placeholder="请填写商品编码" clearable></el-input>
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="drawerProps.row!.description" placeholder="请填写描述" clearable></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="UserDrawer">
import { ref, reactive, onMounted, Ref } from "vue";
// import { genderType } from "@/utils/dict";
import { ElMessage, FormInstance } from "element-plus";
import { Goods } from "@/api/interface";
import UploadImg from "@/components/Upload/Img.vue";
// import UploadImgs from "@/components/Upload/Imgs.vue";
import { getList as getUnit } from "@/api/modules/units";
import { getList as getSpecial } from "@/api/modules/special";
const rules = reactive({
  goodImg: [{ required: true, message: "请上传商品图" }],
  goodName: [{ required: true, message: "请填写商品名" }],
  username: [{ required: true, message: "请填写用户姓名" }],
  // goodPrice: [{ required: true, message: "请填写价格" }],
  goodCode: [{ required: true, message: "请填写商品编码" }]
});
interface selectProps {
  name: string;
  id: number;
}
interface selectSkuProps {
  propertiesName: string;
  propertiesId: number;
  price?: number;
  tradePrice?: number;
  showPrice?: number;
  quantity?: number;
  imageUrl?: string;
  id?: number;
}
interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<Goods.ResGoodList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
  cateList: Array<selectProps>;
  SupplierList: Array<selectProps>;
}

const drawerVisible = ref(false);
const drawerProps: any = ref({
  isView: false,
  title: "",
  row: {},
  cateList: [],
  SupplierList: []
});

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  console.log("params", params);
  drawerProps.value = params;
  drawerVisible.value = true;
  checkList.value = [];
  if (drawerProps.value.row.Sku) {
    skuData.value = drawerProps.value.row.Sku;
    generateSku(drawerProps.value.row.specialIds);
    // tempSkuInfoArray.value = skuData.value;
    checkList.value = drawerProps.value.row.Sku.map(item => item.propertiesName);
  } else {
    skuData.value = [];
    tempSkuInfoArray.value = [];
  }
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  let params = JSON.parse(JSON.stringify(drawerProps.value.row));
  params.specialIds = params.specialIds.join(",");
  params.Sku = skuData.value;
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      await drawerProps.value.api!(params);
      ElMessage.success({ message: `${drawerProps.value.title}商品成功！` });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};
// 单位
const UnitList: any = ref([]);
const getUnitList = () => {
  let newParams = {
    pageNum: 1,
    pageSize: 100,
    name: ""
  };
  getUnit(newParams).then(res => {
    if (res.code == 200) {
      UnitList.value = res.data.list;
    }
  });
};
// 规格
const SpecialList: any = ref([]);
const getSpecialList = () => {
  let newParams = {
    pageNum: 1,
    pageSize: 100,
    name: ""
  };
  getSpecial(newParams).then(res => {
    if (res.code == 200) {
      SpecialList.value = res.data.list;
    }
  });
};
const changeSku = e => {
  console.log(e);
  checkList.value = [];
  generateSku(e);
};
const combineSpecs = (...specsArrays) => {
  // 使用 reduce 和 flatMap 来生成所有可能的组合
  return specsArrays.reduce(
    (acc, specs) => acc.flatMap(accItem => specs.map(spec => [...accItem, spec])),
    [[]] // 初始值是一个空数组的数组，用于开始累积
  );
};
let tempSkuInfoArray: Ref<Array<selectSkuProps>> = ref([]);
const checkList: Ref<Array<string>> = ref([]);
const generateSku = ids => {
  console.log("生成sku");
  let currentSku = SpecialList.value.filter(item => ids.includes(item.id)).map(item => item.specOptions);
  tempSkuInfoArray.value = [];
  console.log("currentSku", currentSku);
  let combinedSkus = combineSpecs(...currentSku);
  console.log("combinedSkus", combinedSkus);
  combinedSkus.forEach(sku => {
    tempSkuInfoArray.value.push({
      propertiesName: sku.map(item => item.name).join(","),
      propertiesId: sku.map(item => item.id).join(",")
    });
  });
  console.log("tempSkuInfoArray", tempSkuInfoArray);
};
const skuData: Ref<Array<selectSkuProps>> = ref([]);
const generateSkuTable = () => {
  console.log("checkList", checkList.value, tempSkuInfoArray.value);
  let tempSkuInfoArrayCopy = tempSkuInfoArray.value.filter(item => {
    return checkList.value.includes(item.propertiesName);
  });
  console.log("tempSkuInfoArray", tempSkuInfoArrayCopy);

  // 创建一个映射表，用于快速查找现有的 SKU
  const existingSkuMap = new Map(skuData.value.map((sku: any) => [sku.propertiesName, sku]));

  // 更新 skuData
  skuData.value = tempSkuInfoArrayCopy.map(item => {
    // 如果映射表中有对应的 SKU，则保留原有的值
    const existingSku: selectSkuProps = existingSkuMap.get(item.propertiesName);
    if (existingSku) {
      return {
        id: existingSku.id,
        propertiesName: existingSku.propertiesName,
        propertiesId: existingSku.propertiesId,
        price: item.price || existingSku.price,
        tradePrice: item.tradePrice || existingSku.tradePrice,
        showPrice: item.showPrice || existingSku.showPrice,
        quantity: item.quantity || existingSku.quantity,
        imageUrl: item.imageUrl || existingSku.imageUrl
      };
    } else {
      // 否则使用新值
      return {
        id: item.id,
        propertiesName: item.propertiesName,
        propertiesId: item.propertiesId,
        price: item.price || 0,
        tradePrice: item.tradePrice || 0,
        showPrice: item.showPrice || 0,
        quantity: item.quantity || 0,
        imageUrl: item.imageUrl || ""
      };
    }
  });
};

onMounted(() => {
  getUnitList();
  getSpecialList();
});
defineExpose({
  acceptParams
});
</script>
